package com.kehutong.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.util.HashID;
import org.coraframework.util.Objects;

public class TemplateReplaceUtil {

    /**
     * 通过反射将模板内容进行替换
     * @param preStr 待替换字符串（模板内容）
     * @param jsonArray 标签说明，JSONArray的字符串格式
     * @param object entity
     * @return 替换后的字符串
     * @throws IllegalAccessException
     */
    public static String replace(String preStr, String jsonArray, Object object) throws Exception {
        // 检查必填参数
        if (Objects.isEmpty(preStr) || Objects.isEmpty(jsonArray) || Objects.isNull(object))
            throw new Exception("请检查参数后重试");

        // 待替换模板内容为空，直接返回原串即可
        JSONArray array = JSONArray.parseArray(jsonArray);
        if (Objects.isEmpty(array))
            return preStr;

        // 缓存模板字段, key对应object的字段, value对应模板字段
        Map<String, String> templateMap = new HashMap<>();
        array.forEach(e -> {
            JSONObject temp = (JSONObject) e;
            String tempVal = temp.getString("value");
            templateMap.put(tempVal.replace("${", "").replace("}", ""), tempVal);
        });

        List<Field> fieldList = new ArrayList<>();
        Class clz = object.getClass();
        while (clz != null) {
            Field[] declaredFields = clz.getDeclaredFields();
            fieldList.addAll(new ArrayList<>(Arrays.asList(declaredFields)));

            clz = clz.getSuperclass();
        }

        for (Field field : fieldList) {
            if (Modifier.isStatic(field.getModifiers()))
                continue;

            if (!field.isAccessible())
                field.setAccessible(true);

            Object val = field.get(object);
            if (Objects.isNull(val))
                continue;

            String name = field.getName();
            if (templateMap.containsKey(name)) {
                if (val instanceof HashID) {
                    preStr = preStr.replace(templateMap.get(name), ((HashID) val).getDesc());
                } else if (val instanceof BigDecimal) {
                    preStr = preStr.replace(templateMap.get(name), BigDecimalUtils.format(((BigDecimal) val)).toPlainString());
                } else {
                    preStr = preStr.replace(templateMap.get(name), String.valueOf(val));
                }
            }
        }
        return preStr;
    }

    /**
     * 替换成腾讯短信模板格式
     * @param preStr 待替换字符串
     * @return
     */
    public static String replaceTencentSms(String preStr) {
        int i = 1;
        String pattern = "\\$\\{(.*?)}";
        // String pattern = "(\\{(.*?)})";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(preStr);
        while (m.find()) {
            preStr = preStr.replaceFirst(pattern, "{" + i + "}");
            i++;
        }

        return preStr;
    }

    public static boolean checkTrim(String preStr) {
        String pattern = "\\$\\{(.*?)}";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(preStr);
        while (m.find()) {
            if (Objects.isEmpty(m.group(1)))
                return true;
        }

        return false;
    }

    public static boolean checkVariables(String preStr) {
        String pattern = "\\$\\{(.*?)}";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(preStr);

        return m.find();
    }

    /**
     * 通过反射将模板内容进行替换
     * @param preStr 用户输入字符串
     * @param jsonArray 模板内容，JSONArray的字符串格式
     * @param object entity
     * @return 替换后的字符串
     * @throws IllegalAccessException
     */
    public static List<String> listTencentSmsParam(String preStr, String jsonArray, Object object) throws Exception {
        // 检查必填参数
        if (Objects.isEmpty(preStr) || Objects.isEmpty(jsonArray) || Objects.isNull(object))
            throw new Exception("请检查参数后重试");

        // 待替换模板内容为空，直接返回原串即可
        JSONArray array = JSONArray.parseArray(jsonArray);
        if (Objects.isEmpty(array))
            return new ArrayList<>();

        List<Field> fieldList = new ArrayList<>();
        Class clz = object.getClass();
        while (clz != null) {
            Field[] declaredFields = clz.getDeclaredFields();
            fieldList.addAll(new ArrayList<>(Arrays.asList(declaredFields)));

            clz = clz.getSuperclass();
        }

        List<String> resultList = new ArrayList<>();
        String pattern = "\\$\\{(.*?)}";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(preStr);
        // 按查找顺序依次获取返回值
        while (m.find()) {
            for (Field field : fieldList) {
                if (Modifier.isStatic(field.getModifiers()))
                    continue;

                if (!field.isAccessible())
                    field.setAccessible(true);

                Object val = field.get(object);
                if (Objects.isNull(val))
                    continue;

                String name = field.getName();
                if (name.equals(m.group(1))) {
                    if (val instanceof HashID) {
                        resultList.add(((HashID) val).getDesc());
                    } else if (val instanceof BigDecimal) {
                        resultList.add(BigDecimalUtils.format(((BigDecimal) val)).toPlainString());
                    } else {
                        resultList.add(String.valueOf(val));
                    }
                }
            }
        }

        return resultList;
    }
}
